import os
from training.msg import FormationRequest,TrainingInsertRequest,GeneralResponse,DataFrameRequest
from iop import BusinessOperation
import psycopg2
import pandas as pd
import matplotlib.pyplot as plt

class SaveInTxtBo(BusinessOperation):
    
    def on_init(self):
        # 检查 SaveInTxtBo 的实例是否具有 filename 属性
        # 如果没有，将其设置为 'formation.txt' 作为默认值
        if not hasattr(self, 'filename'):
            self.filename = 'data.txt'
        # 检查 SaveInTxtBo 的实例是否具有 path 属性
        # 如果没有，将其设置为 '/irisdev/app/data/' 作为默认值
        if not hasattr(self, 'path'):
            self.path = '/irisdev/app/data/'
        # 是否有path
        if not os.path.exists(self.path):
            # 没有的话建立一个
            os.makedirs(self.path)

    def on_formation_request(self, request: FormationRequest):

        with open(os.path.join(self.path, self.filename), 'a') as self.file:
            self.file.write(f'{request.id};{request.BMI};{request.Smoker};{request.Age};{request.Sex}\n')
            # log the message
            self.log_info(f'FormationRequest {request.id} saved in {self.filename}')
        response = GeneralResponse()
        response.status = 'OK'
        return response
            
class PostgresOperation(BusinessOperation):
    
    #  Postgres 数据库操作
    

    def on_init(self):
        """
       
        :return: None
        """
        self.conn = psycopg2.connect(
        host="db",
        database="DemoData",
        user="DemoData",
        password="DemoData",
        port="5432")
        self.conn.autocommit = True

        return None

    def on_tear_down(self):
        """
        关闭链接
        :return: None
        """
        self.conn.close()
        return None

    def insert_training(self,request:TrainingInsertRequest):
        """
        插入postgress数据库
        
        """
        cursor = self.conn.cursor()
        sql = "INSERT INTO public.formation ( Age,BMI ) VALUES ( %s , %s )"
        cursor.execute(sql,(request.Age,request.BMI))
        return None



class DrawLineGraphsOperation(BusinessOperation):
    # 用dataframe画折线图
    def on_init(self):
        return None
    
    def on_tear_down(self):
        return None
    
    def draw_line_graph(self,request:DataFrameRequest):
        df = request.data
        df.plot()
        plt.savefig('/irisdev/app/data/line_graph.png')
        # plt.show()
        return None